/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.xulapa.rs;

import br.com.xulapa.domain.Marca;
import br.com.xulapa.ejb.XulapaBeanRemote;
import com.sun.jersey.api.json.JSONWithPadding;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.ManagedBean;
import javax.annotation.PostConstruct;
import javax.annotation.security.PermitAll;
import javax.ejb.EJB;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.CacheControl;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.EntityTag;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.UriInfo;

/**
 *
 * @author brunolellis
 */
@Path("/xulapa")
@PermitAll
@ManagedBean
//@Consumes({"application/xml", "application/json"})
@Produces({"application/xml", "application/json"})
public class XulapaRS {

    @EJB
    private XulapaBeanRemote xulapa;

    @Context
    private UriInfo uriInfo;

    @Context
    private HttpHeaders httpHeaders;

    @PostConstruct
    private void post() {
        System.out.println("fui construido, então o @ManagedBean funciona!");

    }

    @POST
    @Path("/say")
    @Produces(MediaType.TEXT_PLAIN)
    public String sayXulapa() {
        xulapa.sayXulapa();
        return "xulapaaaa";

    }

    @POST
    @Path("teste")
    public void teste() {
        System.out.println("teste!!!");

    }

    @GET
    @Path("/teste/{param1}/{param2}")
    @Produces(MediaType.TEXT_PLAIN)
    public String testeGet(@PathParam("param1") String param1, @PathParam("param2") String param2) {
        
        return "testestestestestesteste - " + param1 + " - " + param2;

    }

    @OPTIONS
    @Path("/marcas")
    public Response options() {
        System.out.println("%%%%%% OPTIONS em /marcas");
        return Response.ok().header("Access-Control-Allow-Origin", "*").header("Allow", "OPTIONS,POST,GET,HEAD,PUT,DELETE").build();

    }

    @POST
//    @Consumes("application/x-www-form-urlencoded")
    @Consumes({"application/xml", "application/json"})
    @Path("/marcas")
    public Response create(Marca marca) {
//    public Response create(@FormParam("nome") String nome) {
//        Marca marca = new Marca(null, nome);
        System.out.println("######### POST em /marcas " + marca);

        xulapa.createMarca(marca);
        return Response.created(uriInfo.getAbsolutePath()).build();

    }

    @PUT
    @Path("/marcas")
    public void updateMarca(Marca marca) {
        System.out.println("$$$$$$$ PUT em /marcas " + marca);
        xulapa.updateMarca(marca);

        //return Response.noContent().build();

    }

    @DELETE
    @Path("/marcas/{id}")
    public void deleteMarca(@PathParam("id") Long id) {
        System.out.println("&&&&&&&&&&&&&&& DELETE em /marcas/" + id);
        xulapa.deleteMarca(id);

        //return Response.noContent().build();

    }

    @GET
    @Path("/marcas")
    public List<Marca> findAllMarca() {
        System.out.println("!!!! GET em /marcas");
        return xulapa.findAllMarca();

    }

    // todos os tipos de parametros via GET.
    @GET
    @Path("/params")
    public String get(@Context UriInfo ui, @Context HttpHeaders hh) {
        MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
        MultivaluedMap<String, String> pathParams = ui.getPathParameters();

        MultivaluedMap<String, String> headerParams = hh.getRequestHeaders();
        Map<String, Cookie> cookieParams = hh.getCookies();

        System.out.println("*** query");
        Set<String> querySet = queryParams.keySet();
        for (String str : querySet) {
            System.out.println(str);
            System.out.println(queryParams.get(str));
            System.out.println("-----");

        }

        System.out.println("*** path");
        Set<String> pathSet = pathParams.keySet();
        for (String str : pathSet) {
            System.out.println(str);
            System.out.println(pathParams.get(str));
            System.out.println("-----");

        }

        System.out.println("*** header");
        Set<String> headerSet = headerParams.keySet();
        for (String str : headerSet) {
            System.out.println(str);
            System.out.println(headerParams.get(str));
            System.out.println("-----");

        }

        System.out.println("*** cookie");
        Set<String> cookieSet = cookieParams.keySet();
        for (String str : cookieSet) {
            System.out.println(str);
            System.out.println(cookieParams.get(str));
            System.out.println("-----");

        }



        return "";
    }


    // hmmmmm... como pesquisar com REST???
    @GET
    @Path("/findmarcas")
    @Produces({"application/x-javascript", MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public JSONWithPadding findMarcas(@QueryParam("jsoncallback") @DefaultValue("fn") String callback) {
        System.out.println("!!!!! GET em /findmarcas");
        List<Marca> out = xulapa.findAllMarca();

        SearchableResource sr = new SearchableResource(1, 3, 60, out);

        return new JSONWithPadding(
                new GenericEntity<SearchableResource>(sr) {
                }, callback);
    }

    // retirado daqui: http://java.dzone.com/articles/jersey-featuring-jquery-jsonp
    @GET
    @Path("/marcasp")
    @Produces({"application/x-javascript", MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public JSONWithPadding findAllMarcaP(@QueryParam("jsoncallback") @DefaultValue("fn") String callback) {
        List<Marca> out = findAllMarca();

        return new JSONWithPadding(
                new GenericEntity<List<Marca>>(out) {
                }, callback);
    }

    // testes de cache
    @GET
    @Path("/marcas/{id}")
    public Response findMarcaById(@PathParam("id") int id, @Context Request request) {
        Marca marca = xulapa.findMarcaById(id);
        EntityTag tag = new EntityTag(String.valueOf(marca.hashCode()));

        CacheControl cc = new CacheControl();
        cc.setMaxAge(60);

        ResponseBuilder builder = request.evaluatePreconditions(tag);

        if (builder != null) {
            System.out.println("iiiiifffffffff, retorna apenas ");
            builder.cacheControl(cc);
            return builder.build();

        }

        System.out.println("builder == null! foi ao banco");

        builder = Response.ok(marca);
        builder.cacheControl(cc);
        builder.tag(tag);
        return builder.build();

        //return xulapa.findMarcaById(id);

    }

}
